<template>
  <div class="atticle-list-box">
    <van-pull-refresh
      v-model="isLoading"
      success-text="刷新成功"
      @refresh="onRefresh"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
      >
        <article-item
          v-for="item in list"
          :key="item.id"
          :article="item"
        />
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from '@/api/article'
import ArticleItem from '@/components/article-item'

export default {
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  components: {
    ArticleItem
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      timestamp: null,
      error: false,
      isLoading: false
    }
  },
  methods: {
    async onLoad() {
      try {
        const { data: {data: {results, pre_timestamp}} } = await getArticles({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now()
        })

        this.list.push(...results)

        this.loading = false

        if (results.length === 0) {
          this.finished = true
        } else {
          this.timestamp = pre_timestamp
        }
      } catch(err) {
        this.loading = false

        this.error = true
      }

    },
    async onRefresh() {
      try {
        const { data: {data: {results}} } = await getArticles({
          channel_id: this.channel.id,
          timestamp: Date.now()
        })

        this.list.unshift(...results)

        this.isLoading = false
        this.$toast('刷新成功')
      } catch(err) {
        console.log(err)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.atticle-list-box {
  height: 79vh;
  overflow: auto;
}
</style>
